﻿﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.Validation;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Parsers
{
    public class DeviceMessageInfoReadingParser : AbstractMessageParser<IDeviceMessageInfoReading>, IDeviceMessageInfoReadingParser
    {
        public DeviceMessageInfoReadingParser() : base(new DeviceMessageInfoReading())
        {
        }

        public override IDeviceMessageInfoReading Parser(ReadOnlySpan<byte> bytes)
        {
            if (bytes.Length < 2)
                throw new DeviceMessageValidationException(
                    ValidationErrorType.InsufficientDataLength,
                    "读数数据长度不足，至少需要2字节的时间偏移字段",
                    nameof(bytes),
                    "至少 2 字节",
                    $"{bytes.Length} 字节");

            IDeviceMessageInfoReading model = new DeviceMessageInfoReading();

            model.Offset = bytes[..2].ToArray();

            model.State = DeviceMessageSerializerProvider.InfoReadingStatesV1Par.Parser(bytes[2..]);
            Model = model;
            return model;
        }
    }
}
